package com.auto.learning.image.viewpager;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.activity.BookListActivity;
import com.auto.learning.activity.PlayActivity;
import com.auto.learning.activity.VideoPlayActivity;
import com.auto.learning.activity.WebActivity;
import com.auto.learning.bean.BannerItem;
import com.auto.learning.bean.BookBean;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.baidu.mobstat.StatService;
import com.bigkoo.convenientbanner.CBPageAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class NetworkImageHolderView implements CBPageAdapter.Holder<BannerItem>{
    private ImageView imageView;
    Context context;
    
    DisplayImageOptions options;
	
    @Override
    public View createView(Context context) {
    	this.context = context;
    	initImageLoader();
        imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        return imageView;
    }
    
    BookBean m_bookBean = new BookBean();

	@Override
	public void UpdateUI(final Context context, final int position, final BannerItem data, final List<BannerItem> list) {
       try {
    	   //配置好了ImageLoader 参数，为什么还会报内存溢出，不明白？？？？？？？？？？？？
    	   ImageLoader.getInstance().displayImage(data.getBannerImg(), imageView, options);
           imageView.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View view) {
            	   StatService.onEvent(context, "LogEventTypeBannerClick", "Banner图片点击");
            	   switch (data.getType()) {
					case 1:
						if (list != null && list.size() > 0) {
		   					final ArrayList<BookBean> arrayList = new ArrayList<BookBean>();
		   					/*for (int i = position; i < list.size(); i++) {
		   						if (list.get(i).getType() == 1) {
									arrayList.add(list.get(i).getBookModel());
									if (list.get(i).getBookModel().getBookId() == data.getBookModel().getBookId()) {
			   							m_bookBean = list.get(i).getBookModel();
			   						}
								} else 
									break;
		   					}*/
		   					if (data.getBookModel() != null) {
		   						if (data.getBookModel().getNeedBuy() == 2) {
			   						Intent intent = new Intent(context, PlayActivity.class);
			   						intent.putExtra("bookId", data.getBookModel().getBookId());
			   						intent.putExtra("faceImg", data.getBookModel().getFaceImg());
			   						intent.putExtra("canRead", data.getBookModel().getCanRead());
			   						intent.putExtra("needBuy", data.getBookModel().getNeedBuy());
			   						context.startActivity(intent);
								}else {
									arrayList.add(list.get(position).getBookModel());
									if (list.get(position).getBookModel().getBookId() == data.getBookModel().getBookId()) {
			   							m_bookBean = list.get(position).getBookModel();
			   						}
				   					if (MusicPlayManager.getInstance(context).isPlayingBookId()[0] == m_bookBean.getBookId()) {
				   						Intent intent = new Intent(context, PlayActivity.class);
				   						intent.putExtra("bookId", m_bookBean.getBookId());
				   						intent.putExtra("faceImg", m_bookBean.getFaceImg());
				   						intent.putExtra("canRead", m_bookBean.getCanRead());
				   						intent.putExtra("needBuy", m_bookBean.getNeedBuy());
				   						context.startActivity(intent);
									} else 
										playDialog(arrayList, m_bookBean);
								}
							}
						}
						break;
					case 2:
						if (data.getHofModel() != null) {
							Intent intent = new Intent(context,VideoPlayActivity.class);
							intent.putExtra("m_bean", data.getHofModel());
							context.startActivity(intent);
						}
						break;
					case 3:
						if (data.getH5Model() != null && !TextUtils.isEmpty(data.getH5Model().getH5())) {
							Intent intent = new Intent(context, WebActivity.class);
							intent.putExtra("url", data.getH5Model().getH5().replace("{userId}", String.valueOf(SharedPreferencesUtils.getParam(context, HttpRequestHelper.USERID, 0))));
							intent.putExtra("showtitle", true);
							intent.putExtra("title", data.getH5Model().getName()+"");
							intent.putExtra("h5_model", data.getH5Model());
							context.startActivity(intent);
						}
						break;
					case 4:
						if (data.getBookListModel() != null) {
							Intent intent = new Intent(context, BookListActivity.class);
							intent.putExtra("data", data.getBookListModel());
							context.startActivity(intent);
						}
						break;
				}
             }
           });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void showDialog(final ArrayList<BookBean> arrayList,final BookBean bookBean){
		CommonAlertDialog alertDialog = new CommonAlertDialog(context);
		alertDialog.setTextMessage(String.format(context.getResources().getString(R.string.play_size_notice), CommonMethod.calculationNum(bookBean.getProSize()+bookBean.getEnSize() + bookBean.getDoubiSize())));
		alertDialog.setShowTitle(true);
		String[] a = {context.getResources().getString(R.string.app_continue),context.getResources().getString(R.string.app_cancel)};
		alertDialog.setBtns(new DialogListener() {
			
			@Override
			public void okButtonClick(Dialog dialog) {
				play(arrayList,bookBean,false);
				MusicPlayManager.getInstance(context).setShowNetTips(false);
				dialog.dismiss();
			}

			@Override
			public void cancelButtonClick(Dialog dialog) {
				CommonMethod.reordPlayStatus(context, bookBean.getBookId(), true);
				dialog.dismiss();
			}

			@Override
			public void otherButtonClick(Dialog dialog) {
				CommonMethod.reordPlayStatus(context, bookBean.getBookId(), true);
				dialog.dismiss();
			}
		},a);
		alertDialog.show();
	}

	
	public void playDialog(final ArrayList<BookBean> arrayList,final BookBean bookBean){
		if (TemporaryVariable.downLoadedList.contains(bookBean.getBookId())) {
			play(arrayList,bookBean,true);
		}else {
			if ((boolean)SharedPreferencesUtils.getParam(context, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
				play(arrayList,bookBean,true);
			} else {
				switch (CommonMethod.getNetworkState(context)) {
				case 0:
					CommonMethod.makeNotice(context, context.getResources().getString(R.string.connect_err_io));
					break;
				case 1:
					play(arrayList,bookBean, true);
					break;
				case 2:
					showDialog(arrayList,bookBean);
					break;
				}
			}
		}
	}
	
	
	private void play(final ArrayList<BookBean> arrayList,final BookBean bookBean, final boolean isWifi){
		handler.postDelayed(new Runnable() {
			public void run() {
				ArrayList<BookBean> m_list = new ArrayList<BookBean>();
				if (CommonMethod.getNetworkState(context) == 1) {
					m_list.addAll(arrayList);
				}else {
					m_list.add(bookBean);
					int index = arrayList.indexOf(bookBean);
					for (int k = index - 1; k >= 0; k-- ) {
						if (TemporaryVariable.downLoadedList.contains(arrayList.get(k).getBookId())) {
							m_list.add(0, arrayList.get(k));
						} else {
							break;
						}
					}
					for (int i = index + 1; i < arrayList.size(); i++) {
						if (TemporaryVariable.downLoadedList.contains(arrayList.get(i).getBookId())) {
							m_list.add(arrayList.get(i));
						} else {
							break;
						}
					}
				}
				MusicPlayManager.getInstance(context).setPlayList(m_list).setBookId(bookBean.getBookId()).play();
			}
		}, 1500);
		TemporaryVariable.read_list.clear();
		for (int i = 0; i < arrayList.size(); i++) {
			TemporaryVariable.read_list.add(arrayList.get(i).getBookId());
		}
		Intent intent = new Intent(context, PlayActivity.class);
		intent.putExtra("bookId", bookBean.getBookId());
		intent.putExtra("faceImg", bookBean.getFaceImg());
		intent.putExtra("canRead", bookBean.getCanRead());
		intent.putExtra("needBuy", bookBean.getNeedBuy());
		context.startActivity(intent);
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			
		};
	};
	
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.banner)
		.showImageForEmptyUri(R.drawable.banner)
		.showImageOnFail(R.drawable.banner).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}
	
}
